//
//  UpgradeAlertView.swift
//  LeTu
//
//  Created by g1 on 2024/3/5.
//

import UIKit

class UpgradeAlertView: UIView {

    private let rootView: UIWindow? = AppThemeManager.keyWindow()
    private var backgroundView: UIView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configUI()
    }
    
    @objc func toStore() {
        guard let storeUrl = URL(string: Constant.kAppStoreUrl) else { return }
        UIApplication.shared.open(storeUrl)
    }
    
    // MARK: - configUI
    func configUI() {
        
        guard let rootView = rootView else { return }
        
        // 防止多个 AlertView 重复显示
        if rootView.subviews.filter({ $0.isKind(of: AppMiddleAlertView.self) }).count > 0 { return }
                
        backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        
        rootView.addSubview(backgroundView)
        rootView.addSubview(self)
        
        backgroundView.snp.makeConstraints { (make) in
            make.edges.equalTo(rootView)
        }
        snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        addSubview(backView)
        backView.addSubview(topBackView)
        topBackView.addSubview(titleLabel)
        topBackView.addSubview(versionLabel)
        backView.addSubview(upgradeIconImgView)
        backView.addSubview(bottomBackView)
        backView.addSubview(upgradeBtn)
        backView.addSubview(contentLabel)
        
        backView.snp.makeConstraints { make in
            make.width.equalTo(screenFixationWidth-56*2)
            make.center.equalToSuperview()
        }
        topBackView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(30)
            make.height.equalTo(122)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalTo(32)
        }
        versionLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
        }
        upgradeIconImgView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.width.height.equalTo(122)
        }
        upgradeBtn.snp.makeConstraints { make in
            make.left.equalTo(35)
            make.right.equalTo(-35)
            make.height.equalTo(CGFloat.app_btnHeight)
            make.bottom.equalTo(-32)
        }
        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.equalTo(24)
            make.top.equalTo(topBackView.snp.bottom).offset(40)
            make.bottom.equalTo(upgradeBtn.snp.top).offset(-40)
        }
        bottomBackView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(topBackView.snp.bottom)
        }
        
        rootView.layoutIfNeeded()
        topBackView.gradientColors = UIColor.app_themeGradientColors
        upgradeBtn.gradientColors = UIColor.app_themeGradientColors
        
        upgradeBtn.addTarget(self, action: #selector(toStore))
    }
    private lazy var backView = UIView()
    private lazy var topBackView = GradientButton()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = kSetPingFangBlod(26)
        titleLabel.text = "发现新版本"
        titleLabel.textColor = .white
        return titleLabel
    }()
    private lazy var versionLabel: UILabel = {
        let versionLabel = UILabel()
        versionLabel.font = kSetPingFangMedium(14)
        versionLabel.textColor = .white
        return versionLabel
    }()
    private lazy var upgradeIconImgView: UIImageView = {
        let upgradeIconImgView = UIImageView()
        upgradeIconImgView.image = UIImage(named: "app_upgrade_icon")
        upgradeIconImgView.contentMode = .scaleAspectFit
        return upgradeIconImgView
    }()
    private lazy var bottomBackView: UIView = {
        let bottomBackView = UIView()
        bottomBackView.backgroundColor = .white
        return bottomBackView
    }()
    private lazy var contentLabel: UITextView = {
        let contentLabel = UITextView()
        contentLabel.textColor = .app_black
        contentLabel.font = kSetPingFangRegular(14)
        contentLabel.isEditable = false
        contentLabel.textContainerInset = UIEdgeInsets.zero
        return contentLabel
    }()
    private lazy var upgradeBtn: GradientButton = {
        let upgradeBtn = GradientButton()
        upgradeBtn.setTitle("立即升级")
        upgradeBtn.setFont(kSetPingFangBlod(16))
        return upgradeBtn
    }()

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension UpgradeAlertView {
    
    func show(upgradeModel: UpgradeModel) {
        
        guard rootView != nil else { return }
        
        UIView.animate(withDuration: CGFloat.app_alertShowInterval-0.1) {
            self.backgroundView.backgroundColor = .app_customAlertBackgroundColor
        }

        DispatchQueue.main.async {
            self.upgradeBtn.layerCornerRadius(CGFloat.app_btnHeight/2)
            self.topBackView.layerCornerRadius(12, [.topLeft, .topRight])
            self.backView.layerCornerRadius(12, [.bottomLeft, .bottomRight])
        }
        versionLabel.text = upgradeModel.versionName
        
        let content = LanguageManager.shared.currentLanguage == .zh ? upgradeModel.upgradeInstructions : upgradeModel.upgradeInstructionsEnglish
        contentLabel.text = content
        let contentHeight = content.boundingRect(with: CGSize(width: screenFixationWidth-56*2-30*2, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : kSetPingFangRegular(14)], context: nil).height
        contentLabel.snp.updateConstraints { make in
            make.height.equalTo(max(min(contentHeight, 388), 24))
        }
        
        backView.layoutIfNeeded()
    }
    
    private func hide(completion: (() -> Void)? = nil) {
        
        UIView.animate(withDuration: CGFloat.app_alertHidenInterval, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions(rawValue: 0), animations: {
            self.backView.alpha = 0
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        }) { finished in
            guard finished else { return }
            self.removeAppMiddleAlertView()
        }
        
    }
    func removeAppMiddleAlertView() {
        self.backgroundView.removeFromSuperview()
        self.removeFromSuperview()
    }
        
}



